package com.yyfax.common.recyclerview.base;

import android.support.v4.util.SparseArrayCompat;

/**
 * Created by zhy on 16/6/22.
 * https://github.com/hongyangAndroid/baseAdapter
 */
public class ItemViewDelegateManager<T> {
	private SparseArrayCompat<ItemViewDelegate<T>> mDelegateArray = new SparseArrayCompat<>();

	public int getItemViewDelegateCount() {
		return mDelegateArray.size();
	}

	public ItemViewDelegateManager<T> addDelegate(ItemViewDelegate<T> delegate) {
		int viewType = mDelegateArray.size();
		if (delegate != null) {
			mDelegateArray.put(viewType, delegate);
			++viewType;
		}
		return this;
	}

	public ItemViewDelegateManager<T> addDelegate(int viewType, ItemViewDelegate<T> delegate) {
		mDelegateArray.put(viewType, delegate);
		return this;
	}

	public ItemViewDelegateManager<T> removeDelegate(ItemViewDelegate<T> delegate) {
		if (delegate == null) {
			throw new NullPointerException("ItemViewDelegate is null");
		}
		int indexToRemove = mDelegateArray.indexOfValue(delegate);
		if (indexToRemove >= 0) {
			mDelegateArray.removeAt(indexToRemove);
		}
		return this;
	}

	public ItemViewDelegateManager<T> removeDelegate(int itemType) {
		int indexToRemove = mDelegateArray.indexOfKey(itemType);
		if (indexToRemove >= 0) {
			mDelegateArray.removeAt(indexToRemove);
		}
		return this;
	}

	public int getItemViewType(T item, int position) {
		int delegatesCount = mDelegateArray.size();
		for (int i = delegatesCount - 1; i >= 0; i--) {
			ItemViewDelegate<T> delegate = mDelegateArray.valueAt(i);
			if (delegate.isForViewType(item, position)) {
				return mDelegateArray.keyAt(i);
			}
		}
		throw new IllegalArgumentException("No ItemViewDelegate added that matches position=" + position + " in data source");
	}

	public void convert(ViewHolder holder, T item, int position) {
		int delegatesCount = mDelegateArray.size();
		for (int i = 0; i < delegatesCount; i++) {
			ItemViewDelegate<T> delegate = mDelegateArray.valueAt(i);
			if (delegate.isForViewType(item, position)) {
				delegate.convert(holder, item, position);
				return;
			}
		}
		throw new IllegalArgumentException("No ItemViewDelegateManager added that matches position=" + position + " in data source");
	}

	public ItemViewDelegate getItemViewDelegate(int viewType) {
		return mDelegateArray.get(viewType);
	}

	public int getItemViewLayoutId(int viewType) {
		return getItemViewDelegate(viewType).getItemViewLayoutId();
	}

	public int getItemViewType(ItemViewDelegate<T> itemViewDelegate) {
		return mDelegateArray.indexOfValue(itemViewDelegate);
	}
}
